package com.yachang.qym.usbhost.service;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.HelpActivity;
import com.yachang.qym.usbhost.activity.MessageActivity;
import com.yachang.qym.usbhost.activity.VideoChatViewActivity;
import com.yachang.qym.usbhost.model.CallHelpModel;
import com.yachang.qym.usbhost.model.FirePointModel;
import com.yachang.qym.usbhost.model.MessageModel;
import com.yachang.qym.usbhost.model.OutPoliceModel;
import com.yachang.qym.usbhost.model.RoomModel;
import com.yachang.qym.usbhost.model.UserModel;
import com.yachang.qym.usbhost.model.VersionModel;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.DataTransfer;
import com.yachang.qym.usbhost.utils.MessageCache;
import com.yachang.qym.usbhost.utils.NetConnected;
import com.google.gson.Gson;
import com.yachang.qym.usbhost.utils.NotifyIndex;
import com.yachang.qym.usbhost.utils.SendData;
import com.yachang.qym.usbhost.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import static com.yachang.qym.usbhost.utils.API.isNetRunning;
import static com.yachang.qym.usbhost.utils.API.mSocket;
import static com.yachang.qym.usbhost.utils.API.serverUrl;

/**
 * Created by qinyuanmao on 16/5/19.
 */
public class LocationService extends Service{

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:{
                    CallHelpModel model = (CallHelpModel) msg.obj;
                    if(!AllData.isToHelp)
                        showNotification(model);
                }break;
                case 2:{
                    ToastUtil.showToast((String) msg.obj);
                }break;
                case 3:{
                    FirePointModel model = (FirePointModel) msg.obj;
                    showFirePointNotification(model);
                }break;
                case 4:{
                    showMessageNotification((MessageModel) msg.obj);
                }break;
//                case 5:{
//                    AllData.isInPolice = false;
//                    AlertDialog.Builder builder = new AlertDialog.Builder(LocationService.this);
//                    builder.setTitle("提示");
//                    builder.setMessage("您的账号在异地登录！");
//                    builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                            stopService(AllData.usbIntent);
//                            stopService(AllData.locationIntent);
//                            mSocket.disconnect();
//                            mSocket.off();
//                            android.os.Process.killProcess(android.os.Process.myPid());
//                        }
//                    });
//
//                    Dialog dialog = builder.create();
//                    dialog.setCanceledOnTouchOutside(false);
//                    dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//                        @Override
//                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                            if (keyCode == KeyEvent.KEYCODE_BACK) {
//                                return true;
//                            }
//                            return false;
//                        }
//                    });
//                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                    dialog.show();
//                }break;
                case 6:{
                    showHelpNotification((CallHelpModel) msg.obj);
                }
            }
        }
    };

    private Emitter.Listener onGetMessage = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            MessageModel data = new MessageModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            data = gson.fromJson(String.valueOf(jsonObject), MessageModel.class);
            Message message = new Message();
            message.what = 4;
            message.obj = data;
            handler.sendMessage(message);
        }
    };

    private Emitter.Listener onGetHelp = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            CallHelpModel data = new CallHelpModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            data = gson.fromJson(String.valueOf(jsonObject), CallHelpModel.class);
            if(data.getHaveHelper()){
                Message message = new Message();
                message.what = 6;
                message.obj = data;
                handler.sendMessage(message);
            } else if(!data.getUid().equals(AllData.userModel.get_id())) {
                Message message = new Message();
                message.what = 1;
                message.obj = data;
                handler.sendMessage(message);
            }
        }
    };

    private Emitter.Listener onGetVideo = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            RoomModel data = new RoomModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            data = gson.fromJson(String.valueOf(jsonObject), RoomModel.class);
            String roomId = data.getRoomId();
//            if(!roomId.equals("#####")){
                Intent intent = new Intent(LocationService.this, VideoChatViewActivity.class);
                intent.putExtra("roomId", roomId);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
//            }
        }
    };

    private Emitter.Listener onGetExitToHelp = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            CallHelpModel data = new CallHelpModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            data = gson.fromJson(String.valueOf(jsonObject), CallHelpModel.class);
            if(data.getHelperOid().equals(AllData.outPolice_id)){
                AllData.isToHelp = false;
                AllData.isFirstLoad = true;
                SendData.data = SendData.sendFinishHelp();
                SendData.needSend = true;
            }
        }
    };

    private Emitter.Listener onHelperAdd = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            CallHelpModel data = new CallHelpModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            data = gson.fromJson(String.valueOf(jsonObject), CallHelpModel.class);
            if(data.getHaveHelper()){
                if (!(data.getHelperId().equals(AllData.userModel.get_id()))) {
                    AllData.isToHelp = false;
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = "该呼救人员" + data.getHelperName() + "已经去救了!";
                    handler.sendMessage(msg);
                } else {
                    AllData.isToHelp = true;
                    AllData.callHelpModel = data;
                    Message message = new Message();
                    message.what = 2;
                    message.obj = "已开启搜救模式！";
                    handler.sendMessage(message);
                }
            }
        }
    };


    private Emitter.Listener onFirePoint = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            //获取报警点信息，推送到通知栏，开启导航功能
            FirePointModel model = new FirePointModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            model = gson.fromJson(String.valueOf(jsonObject), FirePointModel.class);
            Message message = new Message();
            message.what = 3;
            message.obj = model;
            handler.sendMessage(message);
        }
    };

    private Emitter.Listener onOtherPlaceLogin = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            OutPoliceModel model = new OutPoliceModel();
            Gson gson = new Gson();
            JSONObject jsonObject = (JSONObject) args[0];
            model = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
            if(model != null && model.getUid() != null) {
                if (model.getUid().equals(AllData.userModel.get_id()) || model.getUid().equals("exit")) {
                    Message message = new Message();
                    message.what = 5;
                    message.obj = model;
                    handler.sendMessage(message);
                }
            }
        }
    };

    private void showNotification(CallHelpModel model){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(UsbApplication.getContext())
                        .setSmallIcon(R.mipmap.icon)
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setContentTitle("求救人："+ model.getName())
                        .setContentText("所在高度：" + model.getHigh()+"")
                        .setDefaults(Notification.DEFAULT_ALL);
        Bitmap bitmap = AllData.userBitmap.get(model.getUid());
        mBuilder.setLargeIcon(bitmap);
        mBuilder.setAutoCancel(true);
        Intent intent = new Intent(this, HelpActivity.class);
        intent.putExtra("model", model);
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(pendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) UsbApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify((int) DataTransfer.getNum(model.getMid()), mBuilder.build());
    }

    private void showHelpNotification(CallHelpModel model){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(UsbApplication.getContext())
                        .setSmallIcon(R.mipmap.icon)
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setContentTitle("救援信息")
                        .setContentText(model.getHelperName() + "正在前往救援" + model.getName() + "!")
                        .setDefaults(Notification.DEFAULT_ALL);
        Bitmap bitmap = AllData.userBitmap.get(model.getUid());
        mBuilder.setLargeIcon(bitmap);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager =
                (NotificationManager) UsbApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify((int) DataTransfer.getNum(model.getMid()), mBuilder.build());
    }

    private void showMessageNotification(MessageModel model){
        String uid = "";
        String name = "";
        String mid = "";
        for(OutPoliceModel outPoliceModel: AllData.outPoliceModels){
            if(model.getSenderId().equals(outPoliceModel.get_id())){
                uid = outPoliceModel.getUid();
                name = outPoliceModel.getUserName();
                mid = outPoliceModel.getMid();
                break;
            }
        }
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(UsbApplication.getContext())
                        .setSmallIcon(R.mipmap.icon)
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setContentTitle(name)
                        .setContentText(model.getMsg())
                        .setDefaults(Notification.DEFAULT_ALL);
        Bitmap bitmap = AllData.userBitmap.get(uid);
        mBuilder.setLargeIcon(bitmap);
        Intent intent = new Intent(this, MessageActivity.class);
        intent.putExtra("senderId", model.getSenderId());
        intent.putExtra("senderName", name);
        intent.putExtra("senderUid", uid);
        intent.putExtra("senderMid", mid);
        mBuilder.setAutoCancel(true);
        MessageCache.msg.get(uid).add(model);
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) UsbApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NotifyIndex.MESSAGE, mBuilder.build());
    }

    private void showFirePointNotification(FirePointModel model){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(UsbApplication.getContext())
                        .setSmallIcon(R.mipmap.icon)
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setContentTitle("有新的报警点")
                        .setContentText("所在位置：" + model.getAddress() +"")
                        .setDefaults(Notification.DEFAULT_ALL);
        Resources res = getResources();
        Drawable drawable = res.getDrawable(R.mipmap.fire_icon);
        BitmapDrawable bitmapDrawable=(BitmapDrawable)drawable;
        Bitmap bitmap=bitmapDrawable.getBitmap();
        mBuilder.setLargeIcon(bitmap);
        mBuilder.setAutoCancel(true);
        Intent intent = new Intent(this, com.yachang.qym.usbhost.activity.MainActivity.class);
        intent.putExtra("index", 2);
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) UsbApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NotifyIndex.FIRE_POINT ++ , mBuilder.build());
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(AllData.userModel != null) {
            getFirePoint();
            getApkUpLoad();
            handler.postDelayed(runnable, 0);
        }
        mSocket.on("help", onGetHelp);
        mSocket.on("helpAdd", onHelperAdd);
        mSocket.on("firePoint", onFirePoint);
        mSocket.on("message", onGetMessage);
        mSocket.on("reLogin", onOtherPlaceLogin);
        mSocket.on("video", onGetVideo);
        mSocket.on("exitToHelp", onGetExitToHelp);
        return super.onStartCommand(intent, flags, startId);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(AllData.isInPolice) {
                if (NetConnected.isConnectNet(getApplicationContext())) {
                    if(!isNetRunning){
                        try {
                            mSocket = IO.socket(serverUrl);
                            mSocket.connect();
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("fid", AllData.userModel.getFirecompany_id());
                            map.put("oid", AllData.outPolice_id);
                            JSONObject jsonObject = new JSONObject(map);
                            mSocket.emit("reConnect", jsonObject);
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                        isNetRunning = true;
                    }
                    if ((DataTransfer.getNum(AllData.helpModel.getMachineHigh()) > AllData.LAST_HIGH + 2
                            || DataTransfer.getNum(AllData.helpModel.getMachineHigh()) < AllData.LAST_HIGH - 2)
                            || (DataTransfer.getNum(AllData.helpModel.getMachineTemp()) > AllData.LAST_TEMP + 2
                            || DataTransfer.getNum(AllData.helpModel.getMachineTemp()) < AllData.LAST_TEMP - 2)) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", AllData.outPolice_id);
                        map.put("longitude", AllData.userModel.getLongitude());
                        map.put("latitude", AllData.userModel.getLatitude());
                        map.put("high", DataTransfer.getNum(AllData.helpModel.getMachineHigh()));
                        map.put("temp", DataTransfer.getNum(AllData.helpModel.getMachineTemp()));
                        map.put("nowFloor", AllData.helpModel.getNowFloor());
                        map.put("fid", AllData.userModel.getFirecompany_id());
                        JSONObject jsonObject = new JSONObject(map);
                        API.mSocket.emit("uploadInfo", jsonObject);
                        AllData.LAST_HIGH = (DataTransfer.getNum(AllData.helpModel.getMachineHigh()));
                        AllData.LAST_TEMP = (DataTransfer.getNum(AllData.helpModel.getMachineTemp()));
                    }
                } else {
                    isNetRunning = false;
                }
                handler.postDelayed(runnable, 5000);
            }
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void getFirePoint(){
        String url =  API.getFirePoints() + "?fid=" + AllData.userModel.getFirecompany_id() + "&state=true";
        JsonObjectRequest ja = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Gson gson = new Gson();
                JSONArray array = null;
                try {
                    array = response.getJSONArray("result");
                    for(int i = 0; i < array.length(); i++){
                        FirePointModel model = new FirePointModel();
                        JSONObject object = array.getJSONObject(i);
                        model = gson.fromJson(String.valueOf(object), FirePointModel.class);
                        Message message = new Message();
                        message.what = 3;
                        message.obj = model;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {}
        });
        RequestQueue queue = UsbApplication.getQueue();
        queue.add(ja);
    }

    public void getApkUpLoad(){
        JsonObjectRequest ja = new JsonObjectRequest(Request.Method.GET, API.getApkUrl(), null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Gson gson = new Gson();
                JSONObject object = null;
                try {
                    object = response.getJSONObject("result");
                    VersionModel model = new VersionModel();
                    model = gson.fromJson(String.valueOf(object), VersionModel.class);
                    if(model.getVersion() > Double.valueOf(getAppVersionName(LocationService.this))) {
                        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(getApplicationContext());
                        alertDialog.setTitle("有新版本：" + model.getVersion() + "版");
                        alertDialog.setMessage(model.getDetail());
                        final VersionModel finalModel = model;
                        alertDialog.setPositiveButton("更新",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent();
                                        intent.setAction("android.intent.action.VIEW");
                                        Uri content_url = Uri.parse(finalModel.getUrl());
                                        intent.setData(content_url);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                    }
                                });

                        alertDialog.setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        Dialog ad = alertDialog.create();

                        ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                        ad.setCanceledOnTouchOutside(true);//点击外面区域不会让dialog消失
                        ad.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {}
        });
        RequestQueue queue = UsbApplication.getQueue();
        queue.add(ja);
    }

    private String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo("com.yachang.qym.usbhost", 0);
            versionName = packageInfo.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
